import asyncio
import datetime
import time
import json
import requests
import random
from finance_c2c import local_settings
from urllib.parse import quote
from collections import OrderedDict
from django.shortcuts import HttpResponse
from django.contrib.auth import get_user_model
from django.db.models import Q
from django.shortcuts import render, redirect
from django_filters.rest_framework import DjangoFilterBackend
from rest_framework import filters
from rest_framework import mixins
from rest_framework import status
from rest_framework import viewsets
from rest_framework.decorators import throttle_classes
from rest_framework.response import Response
from rest_framework.views import APIView
from rest_framework.authentication import SessionAuthentication
from rest_framework_jwt.authentication import JSONWebTokenAuthentication
from rest_framework.permissions import IsAuthenticated
from apps.user_operation.permissions import IsOwnerOrReadOnly, IsCompany, MainOrderIsOwnerOrReadOnly
from wechatpy.exceptions import WeChatPayException
from core.tools.models import City
from apps.order.models import TransferErrorCode
from apps.supply_order.utils import UntilPagination
from finance_c2c.local_settings import Config
from core.tools.FormatXmlArray import FormatXmlArray
from core.tools.get_ip import get_ip
from core.wchat.models import WxPayOrder
from core.wchat.WXInstance import KLBWxPay as wx_pay
from core.tools.throttles import TransferRateThrottle
from . import filters as my_filters
from . import models as my_models
from . import serializers as my_serializers
from .models import ReceiverPlace, CartItem, SupplyOrder, Goods, WomaiOrder, WomaiChildOrder
from .serializers import InventorySerializers
from .utils import CustomJSONWebTokenAuthentication
from .womai_api import WoMaiApi
from core.tools.SerializerAPIView import SerializerAPIView
from core.tools.get_datetime import GetDateTime
from core.tl.client import get_TLTransfer
from core.tl.models import TLTransferRecord
from core.tools.func_utils import funcUtils
from apps.czb.models import Orders as CzbOrders
from apps.user_operation.permissions import AddressPermission
from core.zhongxin.client import ZXClient
from core.zhongxin.models import OrderRecord

User = get_user_model()
mai_api = WoMaiApi()


# banner
class BannerViewSet(mixins.ListModelMixin, viewsets.GenericViewSet):
    serializer_class = my_serializers.BannerSerializers
    queryset = my_models.Banner.objects.all()
    filter_backends = (DjangoFilterBackend, filters.SearchFilter)
    filter_class = my_filters.BannerFilter

    def list(self, request, *args, **kwargs):
        queryset = self.filter_queryset(self.get_queryset())

        page = self.paginate_queryset(queryset)
        if page is not None:
            serializer = self.get_serializer(page, many=True)
            return self.get_paginated_response(serializer.data)

        serializer = self.get_serializer(queryset, many=True)
        if request.query_params.get("type") == 2 or request.query_params.get("type") == "2":
            return Response(random.choice(serializer.data))
        return Response(serializer.data)


# 首页专区
class IndexPreViews(mixins.ListModelMixin, viewsets.GenericViewSet):
    serializer_class = my_serializers.IndexPreSerializers
    queryset = my_models.IndexPre.objects.exclude(desc__contains="banner").exclude(status=False)


# 收藏
class CollectViewSet(mixins.ListModelMixin, mixins.CreateModelMixin, mixins.RetrieveModelMixin, mixins.UpdateModelMixin,
                     viewsets.GenericViewSet):
    serializer_class = my_serializers.CollectSerializers
    permission_classes = (IsOwnerOrReadOnly, IsAuthenticated)
    authentication_classes = (JSONWebTokenAuthentication, SessionAuthentication)

    # authentication_classes = (JSONWebTokenAuthentication, BasicAuthentication)

    def get_serializer_class(self):
        if self.action == "list":
            return my_serializers.CollectDetailSerializers
        elif self.action == "update":
            return my_serializers.CollectUpdateSerializers
        else:
            return my_serializers.CollectSerializers

    def get_queryset(self):
        user = self.request.user
        queryset = my_models.Collect.objects.filter(user=user, status=True)
        return queryset


# 收货地址
class ReceiverPlaceViewSet(mixins.CreateModelMixin,
                           mixins.RetrieveModelMixin,
                           mixins.UpdateModelMixin,
                           mixins.ListModelMixin,
                           viewsets.GenericViewSet):
    """
    收货地址
        create:
            新建收货地址
        list:
            收货地址列表
        update:
            修改收货地址, 更改成默认地址
    """
    authentication_classes = (JSONWebTokenAuthentication, SessionAuthentication)
    permission_classes = (IsOwnerOrReadOnly, IsAuthenticated)
    serializer_class = my_serializers.ReceiverPlaceSerializers
    filter_backends = (DjangoFilterBackend, filters.SearchFilter)
    filter_class = my_filters.ReceiverPlaceFilter

    def get_serializer_class(self):
        if self.action == "update" and hasattr(self.request, "data") and self.request.data.get("status") == False:
            return my_serializers.ReceiverPlaceDeleteSerializers
        else:
            return my_serializers.ReceiverPlaceSerializers

    def get_queryset(self):
        return ReceiverPlace.objects.filter(user=self.request.user, status=True)


# 运费
# class YFViewSet(mixins.CreateModelMixin, viewsets.GenericViewSet):
#     serializer_class = my_serializers.YFSerializers
#     permission_classes = (IsOwnerOrReadOnly, IsAuthenticated)
#     authentication_classes = (JSONWebTokenAuthentication, SessionAuthentication)
#
#     def create(self, request, *args, **kwargs):
#         serializer = self.get_serializer(data=request.data)
#         serializer.is_valid(raise_exception=True)
#         data = serializer.validated_data
#         province = data.get("province")
#         user = request.user
#         receiver = user.user_receiver_info.filter(default=True)
#         goods = Goods.objects.get(id=data["goods"])
#         if receiver.exists():
#             rp = receiver.first()
#             province = Province.objects.get(name=rp.province)
#         else:
#             if province:
#                 province = Province.objects.get(name=province)
#             else:
#                 province = None
#         post_free, primage = my_models.YF.objects.get_post_fee_by_goods(goods, data["num"], province=province)
#         return Response(OrderedDict([
#             ('pose_price', post_free),
#             ('primage', primage),
#         ]))


# 商品列表
class GoodsViewSet(mixins.ListModelMixin, mixins.RetrieveModelMixin, viewsets.GenericViewSet):
    """
    商品api
        list: 商品的list
    """
    pagination_class = UntilPagination
    # queryset = Goods.objects.all()
    filter_backends = (DjangoFilterBackend, filters.SearchFilter)
    authentication_classes = (CustomJSONWebTokenAuthentication, SessionAuthentication)

    filter_class = my_filters.GoodsFilter

    # serializer_class = GoodsDetailsSerializers

    def get_serializer_class(self):
        if self.action == "retrieve":
            return my_serializers.GoodsDetailsSerializers
        else:
            return my_serializers.GoodsSerializers

    def get_queryset(self):
        # 我买网数据有些没图片
        goods_id_list = [i[0] for i in my_models.GoodsImage.objects.values_list("goods").distinct()]
        queryset = Goods.objects.select_related("company").filter(can_sale=True, id__in=goods_id_list)
        # return queryset
        if self.request.user.id:
            if ReceiverPlace.objects.filter(user=self.request.user, default=True).exists():
                re_obj = ReceiverPlace.objects.filter(user=self.request.user, default=True).first()
                goods_ids = my_models.Inventory.objects.filter(num__gt=1,
                                                               ware_house__province__name__contains=re_obj.province).values_list(
                    "goods_id", flat=True)
                queryset1 = queryset.filter(company__sign="womaiwang", id__in=goods_ids)
                queryset2 = queryset.exclude(company__sign="womaiwang")
                queryset = queryset1 | queryset2
        if self.kwargs.get(self.lookup_field):
            return queryset.filter(**self.kwargs)
        is_vip_bag = self.request.query_params.get("is_vip_bag")
        index_pre = self.request.query_params.get("index_pre")
        if is_vip_bag == 1 or is_vip_bag == "1":
            return queryset
        elif index_pre:
            if my_models.IndexPre.objects.get(id=index_pre).desc == "会员专区":
                return queryset
            else:
                queryset = queryset.exclude(is_vip_bag=True)
                return queryset
        else:
            queryset = queryset.exclude(is_vip_bag=True)
            return queryset


# 库存信息
class InventoryViewSet(mixins.CreateModelMixin, viewsets.GenericViewSet):
    serializer_class = InventorySerializers
    permission_classes = (IsOwnerOrReadOnly, IsAuthenticated, AddressPermission)
    authentication_classes = (JSONWebTokenAuthentication, SessionAuthentication)

    def create(self, request, *args, **kwargs):
        serializer = self.get_serializer(data=request.data)
        serializer.is_valid(raise_exception=True)
        goods_num_list = self.perform_create(serializer)
        headers = self.get_success_headers(serializer.data)
        data = {"result": goods_num_list}
        return Response(data, status=status.HTTP_201_CREATED, headers=headers)

    def perform_create(self, serializer):
        return serializer.save()


# 区域配送是否有效
class AreaViewSet(mixins.CreateModelMixin, viewsets.GenericViewSet):
    serializer_class = my_serializers.AreaSerializers
    permission_classes = (IsOwnerOrReadOnly, IsAuthenticated)
    authentication_classes = (JSONWebTokenAuthentication, SessionAuthentication)

    def create(self, request, *args, **kwargs):
        serializer = self.get_serializer(data=request.data)
        serializer.is_valid(raise_exception=True)
        goods_num_list = self.perform_create(serializer)
        return Response(OrderedDict([
            ('results', goods_num_list)
        ]), status=status.HTTP_200_OK)

    def perform_create(self, serializer):
        return serializer.save()


# 订单列表
class AllOrderViewSet(mixins.CreateModelMixin,
                      mixins.RetrieveModelMixin,
                      mixins.UpdateModelMixin,
                      mixins.ListModelMixin,
                      viewsets.GenericViewSet):
    """
    订单管理
    """
    filter_backends = (DjangoFilterBackend, filters.SearchFilter)
    pagination_class = UntilPagination
    permission_classes = (MainOrderIsOwnerOrReadOnly, IsAuthenticated)
    authentication_classes = (JSONWebTokenAuthentication, SessionAuthentication)
    # serializer_class = my_serializers.MainOrderDetailsSerializers
    filter_class = my_filters.OrderFilter
    filter_fields = ("order_status",)

    def get_serializer_class(self):
        if self.action == "retrieve":
            return my_serializers.MainOrderDetailsSerializers
        elif self.action == "update":
            return my_serializers.OrderStatusSerializers
        elif self.action == "create":
            return my_serializers.SubmitOrderSerializers
        else:
            return my_serializers.MainOrderSerializers

    def create(self, request, *args, **kwargs):
        serializer = self.get_serializer(data=request.data)
        serializer.is_valid(raise_exception=True)
        supply_order = serializer.save()  # 拿到创建好的基础订单
        data = {"supply_id": supply_order.id}
        return Response(data, status=status.HTTP_201_CREATED)

    def get_queryset(self):
        # 取消订单
        WomaiOrder.objects.cancel_order(user=self.request.user)
        # 去除删除的订单
        return WomaiOrder.objects.filter(supply_order__user=self.request.user).exclude(is_delete=True).exclude(
            order_status=6)

    def list(self, request, *args, **kwargs):
        queryset = self.filter_queryset(self.get_queryset())
        now_time = datetime.datetime.now()
        end_time = now_time - datetime.timedelta(hours=3)
        self.order_qs = queryset.filter(Q(update_time__lte=end_time) & Q(check_status__in=[1, 2, 3]))
        # 如果有未拆单的 或者时间间隔3个小时 并且 check_status 是 1,2,3其中之一
        if self.order_qs.exists():
            loop = asyncio.new_event_loop()
            asyncio.set_event_loop(loop)
            self.loop = loop
            try:
                # 执行coroutine  单线程 直到结果完成
                # results = loop.run_until_complete(self.gather_tasks())
                loop.run_until_complete(self.gather_tasks())
            finally:
                loop.close()
        return super(AllOrderViewSet, self).list(request, *args, **kwargs)

    async def gather_tasks(self):
        tasks = (self.make_future(self.task, i) for i in self.order_qs)
        results = await asyncio.gather(*tasks)
        return results

    async def make_future(self, func, *args):
        # loop.run_in_executor()方法是用来传入需要执行的对象，
        # 以及执行参数，这个方法会维护一个ThreadPoolExecutor()线程池，
        # 如果我们第一个参数是None，run_in_executor()就会把我们的执行对象和参数提交给背后维护的ThreadPoolExecutor()执行，
        # 如果我们传入自己定义的一个线程池，则把执行对象和参数传给我们定义的线程池执行
        future = self.loop.run_in_executor(None, func, *args)
        response = await future
        return response

    @staticmethod
    def task(obj):
        # 未检查的订单 并且是付过款的订单，并且订单是来自我买网需要查看是否需要拆单
        if obj.check_status == 0 and obj.supply_order.wx_pay_type != 0 and obj.company.sign == "womaiwang":
            # 第一次查询判断是否需要拆单
            response = mai_api.get_trade(obj.tid)
            if not response.get("error_response"):
                WomaiOrder.objects.update_order(response, obj)
        # 更新其他状态
        elif obj.check_status == 1 or obj.check_status == 2 and obj.company.sign == "womaiwang":
            response = mai_api.get_trade(obj.tid)
            if not response.get("error_response"):
                obj.update_search_result(response)
        # 被拆过的订单(不需要展示)
        else:
            pass


# 主订单操作(为了查询订单状态)
class BaseOrderViewSet(mixins.ListModelMixin, mixins.RetrieveModelMixin, viewsets.GenericViewSet):
    pagination_class = UntilPagination
    permission_classes = (IsOwnerOrReadOnly, IsAuthenticated)
    authentication_classes = (JSONWebTokenAuthentication, SessionAuthentication)
    serializer_class = my_serializers.BaseOrderSerializers

    def get_queryset(self):
        return SupplyOrder.objects.filter(user=self.request.user, is_active=True)


# H5支付
class PayViewSet(APIView):
    # permission_classes = (IsOwnerOrReadOnly, IsAuthenticated)
    # authentication_classes = (JSONWebTokenAuthentication, SessionAuthentication)
    @staticmethod
    def public_func(request, payment, out_trade_no, trade_type="MWEB"):
        client_ip = get_ip(request)
        pay_dict = {
            "trade_type": trade_type,
            "body": "优品会员",
            "total_fee": str(payment),
            "out_trade_no": out_trade_no,
            "spbill_create_ip": client_ip,
        }
        # 保存数据
        pay_obj = WxPayOrder.objects.create(
            **pay_dict
        )
        return pay_obj, pay_dict

    def post(self, request):
        serializer = my_serializers.PaySerializers(data=request.data)
        if serializer.is_valid(raise_exception=True):
            s_order_pk = serializer.validated_data.get("supply_id")
            s_order = SupplyOrder.objects.get(id=s_order_pk)
            redirect_url = serializer.validated_data.get("redirect_url")
            redirect_url = quote(redirect_url)
            if s_order.wx_pay_type != 0:
                content = {"errmsg": "此订单已经支付了"}
                return Response(content, status=status.HTTP_400_BAD_REQUEST)
            notify_url = Config.host + "/shop/api/receive_h5pay"
            out_trade_no = wx_pay.out_trade_no
            s_order.out_trade_no = out_trade_no
            s_order.save()
            total_fee = str(s_order.payment)
            pay_obj, pay_dict = s_order.public_func(request, total_fee, out_trade_no)
            # 发送请求
            try:
                response = wx_pay.order.create(pay_dict.get("trade_type"), pay_dict.get("body"),
                                               pay_dict.get("total_fee"), notify_url,
                                               out_trade_no=pay_dict.get("out_trade_no"),
                                               client_ip=pay_dict.get("spbill_create_ip"))
                # 更新数据
                pay_obj.update_order_return_data(response)
                mweb_url = response.get("mweb_url")
                mweb_url += "&redirect_url=%s" % redirect_url
                content = {"mweb_url": mweb_url}
                print(content, "content1")
                return Response(content, status=status.HTTP_201_CREATED)
            except WeChatPayException as e:
                if e.errmsg == "201 商户订单号重复":
                    pay_obj, pay_dict = self.public_func(request, s_order)
                    response = wx_pay.order.create(pay_dict.get("trade_type"), pay_dict.get("body"),
                                                   pay_dict.get("total_fee"), notify_url,
                                                   out_trade_no=pay_dict.get("out_trade_no"),
                                                   client_ip=pay_dict.get("spbill_create_ip"))
                    # 更新数据
                    pay_obj.update_order_return_data(response)
                    mweb_url = response.get("mweb_url")
                    mweb_url += "&redirect_url=%s" % redirect_url
                    content = {"mweb_url": mweb_url}
                    print(content, "content2")
                    return Response(content, status=status.HTTP_201_CREATED)
                else:
                    content = {"errmsg": e.errmsg}
                    print(content, "content3")
                    return Response(content, status=status.HTTP_400_BAD_REQUEST)
        return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)

    def get(self, request):
        return render(request, template_name="wx/h5_pay.html")


# 微信支付
class WxPayAPIView(SerializerAPIView):
    """
    微信支付
    """
    permission_classes = (IsAuthenticated,)

    authentication_classes = (JSONWebTokenAuthentication, SessionAuthentication)
    serializer_class = my_serializers.WXPaySerializers

    def post(self, request):
        serializer = self.get_serializer(data=request.data)
        if serializer.is_valid(raise_exception=True):
            s_order_pk = serializer.validated_data.get("supply_id")
            pay_order_model = serializer.validated_data.get("pay_order_model")
            trade_type = "JSAPI"
            notify_url = Config.host + "/shop/api/receive_h5pay"
            openid = request.user.wx_user.openid
            body = "优品会员"
            if pay_order_model == "czb":
                czb_order_instance = CzbOrders.objects.get(id=s_order_pk)
                out_trade_no = czb_order_instance.czb_update_out_trade_no()
                total_fee = str(int(czb_order_instance.payment * 100))
                # total_fee = "1"  # 写死1
                attach = "czb"
                PayViewSet.public_func(request, total_fee, out_trade_no, trade_type=trade_type)
                response = wx_pay.order.create(trade_type, body, total_fee, notify_url, user_id=openid,
                                               out_trade_no=out_trade_no, attach=attach)
            else:
                s_order = SupplyOrder.objects.get(id=s_order_pk)
                out_trade_no = wx_pay.out_trade_no
                s_order.out_trade_no = out_trade_no
                s_order.save()
                total_fee = str(s_order.payment)
                PayViewSet.public_func(request, total_fee, out_trade_no, trade_type=trade_type)
                response = wx_pay.order.create(trade_type, body, total_fee, notify_url, user_id=openid,
                                               out_trade_no=out_trade_no)
            prepay_id = response.get("prepay_id")
            nonce_str = response.get("nonce_str")
            timestamp = int(time.time())
            response["package"] = "prepay_id=%s" % prepay_id
            response["timestamp"] = str(timestamp)
            response.pop("mch_id")
            # 签名8
            sign_content = wx_pay.jsapi.get_jsapi_signature(prepay_id, timestamp=timestamp, nonce_str=nonce_str)
            response["paySign"] = sign_content
            return Response(response, status=status.HTTP_200_OK)


# 前端展示支付结果
class PayResultViewSet(APIView):
    permission_classes = (IsOwnerOrReadOnly, IsAuthenticated)
    authentication_classes = (JSONWebTokenAuthentication, SessionAuthentication)

    def post(self, request):
        serializer = my_serializers.PayResultSerializers(data=request.data)
        serializer.is_valid(raise_exception=True)
        s_order_pk = serializer.validated_data.get("supply_id")
        pay_order_model = serializer.validated_data.get("pay_order_model")
        if pay_order_model == "czb":
            try:
                czb_order_instance = CzbOrders.objects.get(id=s_order_pk)
            except Exception as e:
                content = {"errmsg": "订单未找到", "pay_status": "not_found"}
                return Response(content, status=status.HTTP_400_BAD_REQUEST)
            if czb_order_instance.result == 1:  # 支付成功
                print("网络策略开通，直接支付成功了")
                if czb_order_instance.order_type == 1:  # 加油
                    content = {"errmsg": "SUCCESS", "payment": czb_order_instance.payment,
                               "order_type": czb_order_instance.order_type,
                               "gasName": czb_order_instance.gas.gasName,
                               "gunNumber": czb_order_instance.gunNumber, "oilName": czb_order_instance.oilName}
                    return Response(content, status=status.HTTP_200_OK)
                else:  # 不是加油
                    content = {"errmsg": "SUCCESS", "payment": czb_order_instance.payment,
                               "order_type": czb_order_instance.order_type}
                    return Response(content, status=status.HTTP_200_OK)
            elif czb_order_instance.pay_type == 6 and czb_order_instance.result == 0:  # 中信支付
                if czb_order_instance.order_type == 1:  # 加油
                    out_trade_no = czb_order_instance.out_trade_no
                    zx_client = ZXClient()
                    instance = OrderRecord.objects.get_order_record_instance(out_trade_no)
                    params, response = zx_client.search_order(out_trade_no, instance.requestTimestamp.strftime(
                        "%Y-%m-%d %H:%M:%S"))
                    # 更新数据
                    instance.update_search_response(**response.get("msgBody"))
                    if response.get("msgBody").get("tranResult") == "TRADE_SUCCESS":
                        czb_order_instance.update_pay_result(1, pay_type=6)  # 1:支付成功
                        czb_order_instance.save()
                        czb_order_instance.refresh_from_db()
                    else:
                        content = {"errmsg": "未支付成功", "pay_status": "no_pay"}
                        return Response(content, status=status.HTTP_400_BAD_REQUEST)
                    # end 更新数据
                    content = {"errmsg": "SUCCESS", "payment": czb_order_instance.payment,
                               "order_type": czb_order_instance.order_type,
                               "gasName": czb_order_instance.gas.gasName,
                               "gunNumber": czb_order_instance.gunNumber, "oilName": czb_order_instance.oilName}
                    return Response(content, status=status.HTTP_200_OK)
            else:
                content = {"errmsg": "未支付成功"}
                return Response(content, status=status.HTTP_400_BAD_REQUEST)
        try:
            s_order = SupplyOrder.objects.get(id=s_order_pk)
        except SupplyOrder.DoesNotExist as e:
            print(e)
            content = {"errmsg": "订单未找到", "pay_status": "not_found"}
            return Response(content, status=status.HTTP_400_BAD_REQUEST)
        main_order = s_order.main_base_order.exclude(check_status=3)
        id_list = [i.id for i in main_order]  # 一个产品显示详情，多个显示管理
        if s_order.wx_pay_type != 0:
            payment = s_order.payment / 100.0
            # (1, "正常商品"), (2, "会员礼包")
            if WomaiChildOrder.objects.filter(order_type=2, wm_order__supply_order=s_order).exists():
                order_type = 2
            else:
                order_type = 1
            content = {"errmsg": "SUCCESS", "id_list": id_list, "payment": payment, "order_type": order_type}
            return Response(content, status=status.HTTP_200_OK)
        else:
            content = {"errmsg": "订单未支付", "id_list": id_list, "pay_status": "no_pay"}
            return Response(content, status=status.HTTP_400_BAD_REQUEST)


# 接收微信付款 H5
def receive_h5pay(request):
    body = request.body
    if request.method == "POST":
        # req_dict = FormatXmlArray.xml_to_array(body)
        req_dict = wx_pay.parse_payment_result(body)
        print(req_dict, "print wechat pay resutl")
        check_result = wx_pay.check_signature(req_dict)
        if not check_result:
            re = {"return_code": "ERROR", "return_msg": "ERROR"}
            return HttpResponse(re)
        if req_dict.get("result_code") == "SUCCESS" and req_dict.get("result_code") == "SUCCESS":
            out_trade_no = req_dict.get("out_trade_no")
            wx_pay_obj = WxPayOrder.objects.get(out_trade_no=out_trade_no)
            total_fee = req_dict.get("total_fee")
            # 更新wx付款
            wx_pay_obj.update_order_notify_data(req_dict)
            if req_dict.get("attach") == "czb":
                czb_order_instance = CzbOrders.objects.get(out_trade_no=out_trade_no)
                # if int(total_fee) != czb_order_instance.payment:
                #     re = {"return_code": "SUCCESS", "return_msg": "OK"}
                #     return Response(re, status=status.HTTP_200_OK)
                # 更新加油
                czb_order_instance.update_pay_result(1)
                czb_order_instance.pay_type = 1
                czb_order_instance.save()
            else:
                # 供应链订单start
                s_order = SupplyOrder.objects.get(out_trade_no=out_trade_no)
                if int(total_fee) != s_order.payment:
                    re = {"return_code": "SUCCESS", "return_msg": "OK"}
                    return Response(re, status=status.HTTP_200_OK)
                # s_order 是整个订单， 从中获取我买我网的订单，需要传接口确认预订单
                s_order.update_trade_type_fixed()  # 更新订单
                WomaiChildOrder.objects.update_pay_result(s_order, pay_type="wx")  # 通过支付结果更新其他数据
                # 供应链订单end
        re = {"return_code": "SUCCESS", "return_msg": "OK"}
        re = FormatXmlArray.array_to_xml(re)
    else:
        re = {"return_code": "ERROR", "return_msg": "ERROR"}
    return HttpResponse(re)


# 抢购时间
class ActiveTime(mixins.ListModelMixin, viewsets.GenericViewSet):
    serializer_class = my_serializers.ActiveTimeSerializers
    queryset = my_models.StartTime.objects.all()

    def list(self, request, *args, **kwargs):
        yesterday = GetDateTime.yesterday_date()
        tomorrow = GetDateTime.tomorrow()
        today = datetime.date.today()
        queryset = my_models.StartTime.objects.filter(start_time__gte=yesterday,
                                                      start_time__lte=tomorrow.strftime("%Y-%m-%d 23:59:59"))
        yesterday_count = my_models.StartTime.objects.filter(start_time__gte=yesterday, start_time__lt=today).count()
        today_count = my_models.StartTime.objects.filter(start_time__gte=today, start_time__lt=tomorrow).count()
        start_index = yesterday_count - 1
        end_index = yesterday_count + today_count + 1
        if start_index >= 0 and end_index <= queryset.count():
            queryset = queryset[start_index:end_index]
        serializer = self.get_serializer(queryset, many=True)
        return Response(serializer.data)


# 立刻购买
class BuyNowViewSet(mixins.CreateModelMixin, viewsets.GenericViewSet):
    serializer_class = my_serializers.BuyNowSerializers
    permission_classes = (IsOwnerOrReadOnly, IsAuthenticated)
    authentication_classes = (JSONWebTokenAuthentication, SessionAuthentication)

    def create(self, request, *args, **kwargs):
        serializer = self.get_serializer(data=request.data)
        serializer.is_valid(raise_exception=True)
        company_goods_num_list = self.perform_create(serializer)
        return Response(OrderedDict([
            ('results', company_goods_num_list)
        ]), status=status.HTTP_200_OK)

    def perform_create(self, serializer):
        return serializer.save()


# 购物车
class CartItemViewSet(viewsets.ModelViewSet):
    """
    购物车
        list:
            购物车列表
        create:
            加入购物车
        delete:
            删除购物车订单
    """
    pagination_class = UntilPagination
    # serializer_class = my_serializers.CartItemSerializers
    permission_classes = (IsOwnerOrReadOnly, IsAuthenticated,)
    authentication_classes = (JSONWebTokenAuthentication, SessionAuthentication)

    def get_serializer_class(self):
        if self.action == "update":
            return my_serializers.CartItemUpdateSerializers
        elif self.action == "create":
            return my_serializers.CartItemSerializers
        else:
            return my_serializers.CartItemListSerializers

    def get_queryset(self):
        user = self.request.user
        queryset = my_models.CartItem.objects.select_related("goods_price").prefetch_related(
            "goods_price__price_attr_value_set").filter(user=user, status=1)
        return queryset

    def list(self, request, *args, **kwargs):
        queryset = self.filter_queryset(self.get_queryset())
        # company_qs = queryset.order_by('-update_time').values("goods__company").distinct()
        company_qs = queryset.values("goods__company").distinct()
        list_company = [i.get("goods__company") for i in list(company_qs)]
        company_qs = list(set(list_company))
        page = self.paginate_queryset(company_qs)

        base_list = []
        for i in company_qs:
            d = dict()
            same_shop_cart_qs = queryset.filter(goods__company_id=i)
            shop_info = same_shop_cart_qs.first()
            d["child_order"] = self.get_serializer(same_shop_cart_qs, many=True).data
            d["company"] = my_serializers.CompanySerializers(shop_info.goods.company, many=False).data
            base_list.append(d)
        if page is not None:
            return self.get_paginated_response(base_list)

        return Response(base_list)

    def destroy(self, request, *args, **kwargs):
        instance = self.get_object()
        self.perform_destroy(instance)
        return Response(status=status.HTTP_204_NO_CONTENT)

    def perform_destroy(self, instance):
        instance.status = 3
        instance.save()

    def create(self, request, *args, **kwargs):
        serializer = self.get_serializer(data=request.data)
        serializer.is_valid(raise_exception=True)
        self.perform_create(serializer)
        headers = self.get_success_headers(serializer.data)
        return Response(serializer.data, status=status.HTTP_201_CREATED, headers=headers)


# 购物车个数
class CartItemCount(APIView):
    permission_classes = (IsOwnerOrReadOnly, IsAuthenticated,)
    authentication_classes = (JSONWebTokenAuthentication, SessionAuthentication)

    def get(slef, request):
        user = request.user
        queryset = my_models.CartItem.objects.filter(user=user, status=1)
        count = queryset.count()
        return Response({"count": count})


# 批量删除
class DeleteCartItemViewSet(APIView):
    permission_classes = (IsOwnerOrReadOnly, IsAuthenticated)
    authentication_classes = (JSONWebTokenAuthentication, SessionAuthentication)

    def post(self, request):
        delete_list = request.data.get("delete_list")
        user = request.user
        CartItem.objects.filter(id__in=delete_list, user=user).update(
            status=2
        )
        return Response(status=status.HTTP_200_OK)


# 佣金列表
class IncomeViewSet(mixins.ListModelMixin, viewsets.GenericViewSet):
    serializer_class = my_serializers.IncomeSerializers
    filter_backends = (DjangoFilterBackend, filters.SearchFilter)
    pagination_class = UntilPagination
    permission_classes = (IsOwnerOrReadOnly, IsAuthenticated)
    authentication_classes = (JSONWebTokenAuthentication, SessionAuthentication)
    filter_class = my_filters.IncomeFilter

    def get_queryset(self):
        if self.request.query_params.get("data_type") == "income":
            queryset = my_models.OrderIncome.objects.user_data_base(self.request.user)
        else:
            queryset = my_models.OrderIncome.objects.sales_data_base(self.request.user)
        return queryset.exclude(submit_state=4)


# 数据中心
class CenterDataView(APIView):
    permission_classes = (IsOwnerOrReadOnly, IsAuthenticated)
    authentication_classes = (JSONWebTokenAuthentication, SessionAuthentication)

    def get(self, request):
        user = request.user
        today_order, today_income, today_sales = my_models.OrderIncome.objects.today_data(user)
        this_mouth_order, this_mouth_income, this_mouth_sales = my_models.OrderIncome.objects.this_mouth_data(user)
        last_mouth_order, last_mouth_income, last_mouth_sales = my_models.OrderIncome.objects.last_mouth_data(user)
        total_order, total_income, total_sales = my_models.OrderIncome.objects.total_data(user)
        content = {
            "today_order": today_order,
            "today_income": today_income,
            "today_sales": today_sales,
            "this_mouth_order": this_mouth_order,
            "this_mouth_income": this_mouth_income,
            "this_mouth_sales": this_mouth_sales,
            "last_mouth_order": last_mouth_order,
            "last_mouth_income": last_mouth_income,
            "last_mouth_sales": last_mouth_sales,
            "total_order": total_order,
            "total_income": total_income,
            "total_sales": total_sales,
        }
        return Response(OrderedDict([('result', content)]))


# 物流信息查询
class LogisticsViewSet(mixins.ListModelMixin, viewsets.GenericViewSet):
    authentication_classes = (JSONWebTokenAuthentication, SessionAuthentication)
    permission_classes = (IsAuthenticated,)
    serializer_class = my_serializers.LogisticsSerializers
    filter_backends = (DjangoFilterBackend, filters.SearchFilter)
    filter_class = my_filters.LogisticsFilter

    def get_queryset(self):
        user = self.request.user
        return my_models.Logistics.objects.filter(order__supply_order__user=user)

    def list(self, request, *args, **kwargs):
        queryset = self.filter_queryset(self.get_queryset())

        page = self.paginate_queryset(queryset)
        if page is not None:
            serializer = self.get_serializer(page, many=True)
            return self.get_paginated_response(serializer.data)
        instance = queryset.first()
        odd_numbers, post_company = my_serializers.MainOrderDetailsSerializers.logistics_content(instance.order)
        queryset = instance.logistics_record.all()
        serializer = my_serializers.PostRecordSerializers(queryset, many=True)
        return Response(OrderedDict([("record", serializer.data),
                                     ("odd_numbers", odd_numbers),
                                     ("post_company", post_company)]))


# 银行卡列表标识
class BankSign(mixins.ListModelMixin, viewsets.GenericViewSet):
    serializer_class = my_serializers.BankCodeSerializers
    queryset = my_serializers.BankCode.objects.all()


# 协程测试
class TestViewSet(APIView):
    def get(self, request):
        start_time = time.time()
        # Django视图函数执行，不在主线程中 不能 loop = asyncio.get_event_loop()
        loop = asyncio.new_event_loop()
        asyncio.set_event_loop(loop)
        self.loop = loop
        try:
            # 执行coroutine  单线程 直到结果完成
            results = loop.run_until_complete(self.gather_tasks())
        finally:
            loop.close()
        end_time = time.time()
        return Response({'results': results, 'cost_time': (end_time - start_time)})

    async def gather_tasks(self):
        now_time = datetime.datetime.now()
        end_time = now_time - datetime.timedelta(hours=3)
        order_qs = WomaiOrder.objects.filter(update_time__lte=end_time).exclude(state=1)
        tasks = (self.make_future(mai_api.get_trade, "201902181604142188083334") for i in range(20))
        # tasks = (
        #     self.make_future(self.io_task1, 2),
        #     self.make_future(self.io_task2, 2)
        # )
        results = await asyncio.gather(*tasks)
        # results = await asyncio.wait(tasks)
        return results

    async def make_future(self, func, *args):
        future = self.loop.run_in_executor(None, func, *args)
        response = await future
        return response

    def io_task1(self, sleep_time):
        time.sleep(sleep_time)
        return 66

    def io_task2(self, sleep_time):
        time.sleep(sleep_time)
        return 77


# 提现
class TransferViewSet(SerializerAPIView):
    permission_classes = (IsOwnerOrReadOnly, IsAuthenticated)
    authentication_classes = (JSONWebTokenAuthentication, SessionAuthentication)
    serializer_class = my_serializers.TransferSerializers

    # 通联支付通道提现
    def tl_transfer(self, user, cash):
        tl_user_id = user.userprofileextend.get_tl_user_id()
        tl_transfer_instance = get_TLTransfer()
        SHDD = funcUtils.unique_value
        cash = str(cash)
        response = tl_transfer_instance.transfer_b2c(tl_user_id, cash, SHDD)
        envelope = response.get("envelope")
        body = envelope.get("body")
        head = envelope.get("head")
        timestamp = head.get("timestamp")
        resCls = body.get("resCls")  # "00" 成功 "01" 失败
        record_obj = my_models.TransferRecord.objects.transfer_views(cash, user, SHDD, transfer_type=3)
        if resCls == "00":
            returnValue = body.get("returnValue")
            resMsg = returnValue.get("JYMS")
            TLDD = returnValue.get("TLDD")
            data = {"JYMS": resMsg, "TLDD": TLDD, "timestamp": timestamp, "resCls": resCls, "cash": cash, "SHDD": SHDD}
            TLTransferRecord.objects.create(**data)
            record_obj.status = True
            record_obj.save()
            return "SUCCESS", record_obj
        else:
            resMsg = body.get("resMsg")
            TLDD = None
            content = {"msg": resMsg}
            data = {"JYMS": resMsg, "TLDD": TLDD, "timestamp": timestamp, "resCls": resCls, "cash": cash, "SHDD": SHDD}
            TLTransferRecord.objects.create(**data)
            return Response(content, status=status.HTTP_400_BAD_REQUEST)

    # 微信通道提现
    def wx_transfer(self, user, cash, transfer_type="qianbao"):
        """
        :param user:
        :param cash: 金额
        :param transfer_type: 微信提现方式, 零钱，卡
        :return:
        """
        desc = "收益提现"
        out_trade_no = wx_pay.out_trade_no
        try:
            if transfer_type == "qianbao" and user.wx_user:
                openid = user.wx_user.openid
                info = wx_pay.transfer.transfer(openid, cash, desc, check_name="NO_CHECK", out_trade_no=out_trade_no)
            else:
                if user.real_name and user.bank_card_no:
                    info = wx_pay.transfer.transfer_bankcard(user.real_name, user.bank_card_no, user.bank.code, cash,
                                                             desc=desc, out_trade_no=out_trade_no)
                else:
                    content = {"msg": "填写真实姓名和银行卡号"}
                    return Response(content, status=status.HTTP_400_BAD_REQUEST)
        except Exception as e:
            info = e.response.content
            info = FormatXmlArray.xml_to_array(info)
        info["again"] = False
        transfer_obj = TransferErrorCode.objects.create_data(info)
        partner_trade_no = transfer_obj.partner_trade_no
        record_obj = my_models.TransferRecord.objects.transfer_views(cash, user, partner_trade_no)
        if transfer_obj.return_code == "SUCCESS":
            if transfer_obj.result_code == "SUCCESS":
                record_obj.status = True
                record_obj.save()
                return "SUCCESS", record_obj
            else:
                if transfer_obj.err_code == "SYSTEMERROR":
                    # 这里需要查询接口，确认此次付款结果
                    result = wx_pay.query_transfer_order(out_trade_no)
                    transfer_obj.update_status(result)
                    if transfer_obj.result_code == "SUCCESS":
                        record_obj.status = True
                        record_obj.save()
                        return "SUCCESS", record_obj
                    else:
                        content = {"msg": transfer_obj.err_code_des}
                        return Response(content, status=status.HTTP_400_BAD_REQUEST)
                else:
                    content = {"msg": transfer_obj.err_code_des}
                    return Response(content, status=status.HTTP_400_BAD_REQUEST)
        else:
            content = {"msg": transfer_obj.return_msg}
            return Response(content, status=status.HTTP_400_BAD_REQUEST)

    @throttle_classes([TransferRateThrottle])
    def post(self, request):
        """
        提现到微信钱包  wx_qianbao 提现到银行卡wx_crad 提现到通联钱包 你就写tonglian
        :param request:
        :return:
        """
        serializer = self.get_serializer(data=request.data)
        serializer.is_valid(raise_exception=True)
        transfer_type = serializer.validated_data.get("transfer_type")  # "wx_qianbao, wx_crad, tonglianqianbao,"
        user = request.user
        if not user.can_transfer:
            content = {"status": "error", "msg": "不可提现"}
            return Response(content, status=status.HTTP_400_BAD_REQUEST)
        amount, queryset = my_models.OrderIncome.objects.transfer_income(user)
        if amount < 1000:
            content = {"msg": "最低100元才可以提现哦亲"}
            return Response(content, status=status.HTTP_400_BAD_REQUEST)
        if "wx" in transfer_type:
            if "qianbao" in transfer_type:
                transfer_status = self.wx_transfer(user, amount, transfer_type="qianbao")
            else:
                transfer_status = self.wx_transfer(user, amount, transfer_type="card")
        else:
            transfer_status = self.tl_transfer(user, amount)
        if isinstance(transfer_status, tuple):
            if transfer_status[0] == "SUCCESS":
                content = {"msg": "提现成功，最晚T+1到账，请注意查收"}
                for i in queryset:
                    i.transfer_record.add(transfer_status[1])
                queryset.update(submit_state=4)  # 更新状态
                return Response(content, status=status.HTTP_200_OK)
            else:
                pass
        else:
            return transfer_status

    def get(self, request):
        user = request.user
        today_order, today_income, today_sales = my_models.OrderIncome.objects.today_data(user)
        income, queryset = my_models.OrderIncome.objects.income_sum(user)
        return Response(OrderedDict([("today_order", today_order),
                                     ("today_income", today_income),
                                     ("today_sales", today_sales),
                                     ("income", income)
                                     ]))


# 提现记录
class TransferRecord(mixins.ListModelMixin, viewsets.GenericViewSet):
    serializer_class = my_serializers.TransferRecordSerializers
    permission_classes = (IsOwnerOrReadOnly, IsAuthenticated)
    authentication_classes = (JSONWebTokenAuthentication, SessionAuthentication)
    filter_backends = (DjangoFilterBackend, filters.SearchFilter)
    filter_class = my_filters.TransferFilter
    pagination_class = UntilPagination

    def get_queryset(self):
        user = self.request.user
        queryset = my_models.TransferRecord.objects.filter(status=True, user=user)
        return queryset


# 商品类别
class CategoryViewSet(mixins.ListModelMixin, viewsets.GenericViewSet):
    queryset = my_models.Category.objects.all()
    serializer_class = my_serializers.CategorySerializers
    throttle_classes = (TransferRateThrottle,)


class TestIncome(APIView):
    def get(self, request):
        from .models import OrderIncome
        s_order = SupplyOrder.objects.get(id=118)
        parent_order = s_order.main_base_order.all()
        for parent in parent_order:
            for child in parent.child_order.all():
                base_income = OrderIncome.objects.create_income(child)
                if base_income:
                    OrderIncome.objects.create_other_income(base_income)
        return Response({"HELLO": "WORLD"})


class WaitPay(APIView):
    permission_classes = (IsAuthenticated,)
    authentication_classes = (JSONWebTokenAuthentication, SessionAuthentication)

    def get(self, request):
        base_queryset = my_models.WomaiOrder.objects.filter(supply_order__user=request.user)
        wait_pay_count = base_queryset.filter(order_status=1).count()
        wait_send_count = base_queryset.filter(order_status=2).count()
        wait_receive_count = base_queryset.filter(order_status=3).count()
        content = {"wait_pay_count": wait_pay_count, "wait_send_count": wait_send_count,
                   "wait_receive_count": wait_receive_count}
        return Response(content)


# -----------------------------后台------------------------------


# 子订单管理(发起售后, 用户)
class ChildOrderViewSet(mixins.ListModelMixin, mixins.RetrieveModelMixin, mixins.UpdateModelMixin,
                        viewsets.GenericViewSet):
    """
    子订单
        Update:发起售后
    """
    permission_classes = (IsAuthenticated,)
    authentication_classes = (JSONWebTokenAuthentication, SessionAuthentication)
    pagination_class = UntilPagination
    filter_backends = (DjangoFilterBackend, filters.SearchFilter)
    filter_class = my_filters.ChildOrderFilter

    def get_serializer_class(self):
        if self.action == "update":
            return my_serializers.UpdateWomaiChildOrderSerializers
        else:
            return my_serializers.WomaiChildOrderSerializers

    def get_queryset(self):
        user = self.request.user
        return my_models.WomaiChildOrder.objects.filter(wm_order__supply_order__user=user)
        # return my_models.WomaiChildOrder.objects.filter(after_sale=1)


# 申请退款后台（商户）
class Refund(mixins.ListModelMixin, mixins.RetrieveModelMixin, mixins.UpdateModelMixin, viewsets.GenericViewSet):
    serializer_class = my_serializers.RefundSerializers
    pagination_class = UntilPagination
    filter_backends = (DjangoFilterBackend, filters.SearchFilter)
    permission_classes = (IsAuthenticated, IsCompany)
    authentication_classes = (JSONWebTokenAuthentication, SessionAuthentication)
    filter_fields = ("after_sale",)

    def get_queryset(self):
        queryset = WomaiChildOrder.objects.get_after_sale()
        # 目前只用的微信付款，如果加上其他付款需要改
        queryset = queryset.exclude(wm_order__supply_order__wx_pay_type=0)
        # 会员礼包不可以申请售后
        if self.request.user.company.sign == "youpinhuiyuan":
            # queryset = queryset.filter(goods__is_vip_bag=False)
            pass

        else:
            # queryset = queryset.filter(goods__company=self.request.user.company, goods__is_vip_bag=False)
            queryset = queryset.filter(goods__company=self.request.user.company)
        return queryset


# 物流订单信息
class PostOrder(mixins.ListModelMixin, mixins.RetrieveModelMixin, viewsets.GenericViewSet):
    pagination_class = UntilPagination
    filter_backends = (DjangoFilterBackend, filters.SearchFilter)
    permission_classes = (IsAuthenticated, IsCompany)
    authentication_classes = (JSONWebTokenAuthentication, SessionAuthentication)
    filter_class = my_filters.SendGoodsFilter

    def get_serializer_class(self):
        return my_serializers.AdminMainOrderSerializers

    def get_queryset(self):
        queryset = WomaiOrder.objects.filter(is_delete=False).exclude(order_status=1).exclude(order_status=5).exclude(
            company__sign="womaiwang"
        )
        if self.request.user.company.sign != "youpinhuiyuan":
            queryset = queryset.filter(company=self.request.user.company)
        return queryset


# 物流订单信息
class PostGoods(mixins.UpdateModelMixin, mixins.CreateModelMixin, viewsets.GenericViewSet):
    permission_classes = (IsAuthenticated, IsCompany)
    authentication_classes = (JSONWebTokenAuthentication, SessionAuthentication)
    serializer_class = my_serializers.LogisticsSerializers
    queryset = my_serializers.Logistics.objects.all()

    def perform_create(self, serializer):
        return serializer.save()

    def create(self, request, *args, **kwargs):
        serializer = self.get_serializer(data=request.data)
        serializer.is_valid(raise_exception=True)
        instance = self.perform_create(serializer)
        order = instance.order
        order.order_status = 3
        order.save()
        headers = self.get_success_headers(serializer.data)
        return Response(serializer.data, status=status.HTTP_201_CREATED, headers=headers)

    def update(self, request, *args, **kwargs):
        partial = kwargs.pop('partial', False)
        instance = self.get_object()
        serializer = self.get_serializer(instance, data=request.data, partial=partial)
        serializer.is_valid(raise_exception=True)
        self.perform_update(serializer)

        if getattr(instance, '_prefetched_objects_cache', None):
            # If 'prefetch_related' has been applied to a queryset, we need to
            # forcibly invalidate the prefetch cache on the instance.
            instance._prefetched_objects_cache = {}
        order = instance.order
        order.order_status = 3
        order.save()
        return Response(serializer.data)


class GetLocation(APIView):
    def get(self, request, *args, **kwargs):
        key = local_settings.TXMapKey
        SecretKey = local_settings.SecretKey
        location = request.query_params.get("location")
        data = {"key": key, "location": location}
        from core.tools.encryption import hashlib_md5
        string = "/ws/geocoder/v1?key={key}&location={location}{SecretKey}".format(key=data.get("key"),
                                                                                   location=data.get("location"),
                                                                                   SecretKey=SecretKey)
        sig = hashlib_md5(string)
        data["sig"] = sig
        url = "https://apis.map.qq.com/ws/geocoder/v1?key={key}&location={location}&sig={sig}".format(**data)
        response = requests.get(url)
        response = json.loads(response.content)
        return Response(response)


class GetProvinceByCity(APIView):
    def get(self, request, *args, **kwargs):
        city = request.query_params.get("city")
        queryset = City.objects.filter(name=city)
        if not queryset.exists():
            return Response(status=status.HTTP_404_NOT_FOUND)
        else:
            province = queryset.first().province.name
            response = {"province": province}
            return Response(response, status=status.HTTP_200_OK)


# 物流公司
class PostCompanyViewSet(mixins.ListModelMixin, viewsets.GenericViewSet):
    serializer_class = my_serializers.PostCompanySerializers
    queryset = my_models.PostCompany.objects.all()[:50]


# 更新价格
class UpdatePrice(APIView):
    def post(self, request, *args, **kwargs):
        goods_list = request.data.get("goods_list")
        if isinstance(goods_list, str):
            goods_list = json.loads(goods_list)
        for i in goods_list:
            try:
                obj = Goods.objects.get(goodsid=i.get("product_bn"))
                mktprice = i.get("mktprice")
                mktprice = int(mktprice)
                obj.other_shop_sales_price = mktprice
                if mktprice < obj.cost:
                    obj.can_sale = False
                obj.save()
            except Exception as e:
                pass
        response = "SUCCESS"
        return Response(response)


# ---------------------------未完成------------------------------

# 接收微信退款
def receive_refund(request):
    body = request.body
    req_dict = FormatXmlArray.xml_to_array(body)
    re = {"return_code": "SUCCESS", "return_msg": "OK"}
    re = FormatXmlArray.array_to_xml(re)
    return HttpResponse(re)


# 测试异步任务
def test_async(request):
    from .tasks import async_task
    r = async_task.delay()
    print(r)
    return HttpResponse("SUCCESS")


# ggcard

# class GGCardViewSets(mixins.RetrieveModelMixin, viewsets.GenericViewSet, mixins.UpdateModelMixin):
#     lookup_field = "key"
#     serializer_class = my_serializers.GGCardOrderSerializers
#
#     def get_serializer_class(self):
#         if self.action == "update":
#             return my_serializers.GGCardOrderUpdateSerializers
#         else:
#             return my_serializers.GGCardOrderSerializers
